{% extends 'base.html' %}
{% load static %}

{% block title %}告警通知配置 - Allen监控系统{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>告警通知配置</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#notificationModal">
            <i class="fas fa-plus"></i> 新增通知方式
        </button>
    </div>

    <!-- 通知方式列表 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>名称</th>
                            <th>类型</th>
                            <th>接收人</th>
                            <th>告警级别</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for notification in notifications %}
                        <tr>
                            <td>{{ notification.name }}</td>
                            <td>{{ notification.get_type_display }}</td>
                            <td>{{ notification.recipients }}</td>
                            <td>
                                {% for level in notification.alert_levels %}
                                <span class="badge {% if level == 'critical' %}bg-danger
                                                  {% elif level == 'warning' %}bg-warning
                                                  {% else %}bg-info{% endif %}">
                                    {{ level|upper }}
                                </span>
                                {% endfor %}
                            </td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-status" type="checkbox"
                                           data-id="{{ notification.id }}"
                                           {% if notification.is_active %}checked{% endif %}>
                                </div>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-primary edit-notification"
                                        data-id="{{ notification.id }}"
                                        data-bs-toggle="modal"
                                        data-bs-target="#notificationModal">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-notification"
                                        data-id="{{ notification.id }}">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button class="btn btn-sm btn-info test-notification"
                                        data-id="{{ notification.id }}">
                                    <i class="fas fa-paper-plane"></i>
                                </button>
                            </td>
                        </tr>
                        {% empty %}
                        <tr>
                            <td colspan="6" class="text-center">暂无通知配置</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 通知配置模态框 -->
<div class="modal fade" id="notificationModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">通知配置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="notificationForm">
                    {% csrf_token %}
                    <input type="hidden" name="id" id="notificationId">
                    
                    <div class="mb-3">
                        <label class="form-label">名称</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">通知类型</label>
                        <select class="form-select" name="type" id="notificationType" required>
                            <option value="email">邮件</option>
                            <option value="sms">短信</option>
                            <option value="webhook">Webhook</option>
                            <option value="dingtalk">钉钉</option>
                            <option value="feishu">飞书</option>
                            <option value="wecom">企业微信</option>
                            <option value="telegram">Telegram</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">告警级别</label>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="alert_levels" value="critical" id="levelCritical">
                            <label class="form-check-label" for="levelCritical">
                                严重
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="alert_levels" value="warning" id="levelWarning">
                            <label class="form-check-label" for="levelWarning">
                                警告
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="alert_levels" value="info" id="levelInfo">
                            <label class="form-check-label" for="levelInfo">
                                信息
                            </label>
                        </div>
                    </div>
                    
                    <!-- 邮件配置 -->
                    <div id="emailConfig" class="notification-config">
                        <div class="mb-3">
                            <label class="form-label">SMTP服务器</label>
                            <input type="text" class="form-control" name="smtp_host" placeholder="例如: smtp.gmail.com">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">SMTP端口</label>
                            <input type="number" class="form-control" name="smtp_port" placeholder="例如: 587">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">SMTP用户名</label>
                            <input type="text" class="form-control" name="smtp_username" placeholder="邮箱账号">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">SMTP密码</label>
                            <input type="password" class="form-control" name="smtp_password" placeholder="邮箱密码或应用专用密码">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">发件人邮箱</label>
                            <input type="email" class="form-control" name="smtp_from_email" placeholder="发件人邮箱地址">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">使用SSL/TLS</label>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="smtp_use_tls" id="smtpUseTls">
                                <label class="form-check-label" for="smtpUseTls">
                                    启用SSL/TLS加密
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <button type="button" class="btn btn-info" id="testSmtpConfig">
                                <i class="fas fa-paper-plane"></i> 测试SMTP配置
                            </button>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">收件人</label>
                            <input type="text" class="form-control" name="email_recipients" 
                                   placeholder="多个邮箱用逗号分隔">
                        </div>
                    </div>
                    
                    <!-- 短信配置 -->
                    <div id="smsConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">API URL</label>
                            <input type="url" class="form-control" name="sms_api_url" 
                                   placeholder="短信服务商API地址">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">API Key</label>
                            <input type="text" class="form-control" name="sms_api_key" 
                                   placeholder="短信服务商提供的API密钥">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">API Secret</label>
                            <input type="password" class="form-control" name="sms_api_secret" 
                                   placeholder="短信服务商提供的API密钥密文">
                        </div>
                        <div class="mb-3">
                            <button type="button" class="btn btn-info" id="testSmsConfig">
                                <i class="fas fa-paper-plane"></i> 测试短信配置
                            </button>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">手机号码</label>
                            <input type="text" class="form-control" name="phone_numbers" 
                                   placeholder="多个号码用逗号分隔">
                        </div>
                    </div>
                    
                    <!-- Webhook配置 -->
                    <div id="webhookConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">Webhook URL</label>
                            <input type="url" class="form-control" name="webhook_url">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">请求方法</label>
                            <select class="form-select" name="webhook_method">
                                <option value="POST">POST</option>
                                <option value="GET">GET</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">请求头</label>
                            <textarea class="form-control" name="webhook_headers" rows="3"
                                    placeholder='{"Content-Type": "application/json"}'></textarea>
                        </div>
                    </div>

                    <!-- 钉钉配置 -->
                    <div id="dingtalkConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">Webhook URL</label>
                            <input type="url" class="form-control" name="dingtalk_webhook_url" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">加签密钥（可选）</label>
                            <input type="text" class="form-control" name="dingtalk_secret">
                        </div>
                    </div>

                    <!-- 飞书配置 -->
                    <div id="feishuConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">Webhook URL</label>
                            <input type="url" class="form-control" name="feishu_webhook_url" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">加签密钥（可选）</label>
                            <input type="text" class="form-control" name="feishu_secret">
                        </div>
                    </div>

                    <!-- Server酱配置 -->
                    <div id="serverchanConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">SCKEY</label>
                            <input type="text" class="form-control" name="serverchan_sckey" required>
                        </div>
                    </div>

                    <!-- 企业微信配置 -->
                    <div id="wecomConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">企业ID (CorpID)</label>
                            <input type="text" class="form-control" name="wecom_corp_id" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">应用密钥 (Secret)</label>
                            <input type="text" class="form-control" name="wecom_corp_secret" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">应用ID (AgentID)</label>
                            <input type="text" class="form-control" name="wecom_agent_id" required>
                        </div>
                    </div>

                    <!-- Telegram配置 -->
                    <div id="telegramConfig" class="notification-config" style="display: none;">
                        <div class="mb-3">
                            <label class="form-label">Bot Token</label>
                            <input type="text" class="form-control" name="telegram_bot_token" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Chat ID</label>
                            <input type="text" class="form-control" name="telegram_chat_id" required>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="saveNotification">保存</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 切换通知类型时显示/隐藏相应配置
    $('#notificationType').change(function() {
        $('.notification-config').hide();
        $(`#${$(this).val()}Config`).show();
    });

    // 测试SMTP配置
    $('#testSmtpConfig').click(function() {
        const smtpData = {
            smtp_host: $('input[name="smtp_host"]').val(),
            smtp_port: $('input[name="smtp_port"]').val(),
            smtp_username: $('input[name="smtp_username"]').val(),
            smtp_password: $('input[name="smtp_password"]').val(),
            smtp_from_email: $('input[name="smtp_from_email"]').val(),
            smtp_use_tls: $('input[name="smtp_use_tls"]').prop('checked'),
            test_email: $('input[name="email_recipients"]').val().split(',')[0],
            csrfmiddlewaretoken: '{{ csrf_token }}'
        };

        // 禁用测试按钮
        const $button = $(this);
        $button.prop('disabled', true);
        $button.html('<i class="fas fa-spinner fa-spin"></i> 测试中...');

        $.ajax({
            url: '{% url "test_smtp_config" %}',
            type: 'POST',
            data: smtpData,
            success: function(response) {
                if (response.status === 'success') {
                    alert('SMTP配置测试成功！测试邮件已发送。');
                } else {
                    alert('SMTP配置测试失败：' + response.message);
                }
            },
            error: function() {
                alert('测试请求发送失败，请检查网络连接。');
            },
            complete: function() {
                // 恢复测试按钮
                $button.prop('disabled', false);
                $button.html('<i class="fas fa-paper-plane"></i> 测试SMTP配置');
            }
        });
    });

    // 测试短信配置
    $('#testSmsConfig').click(function() {
        const smsData = {
            api_url: $('input[name="sms_api_url"]').val(),
            api_key: $('input[name="sms_api_key"]').val(),
            api_secret: $('input[name="sms_api_secret"]').val(),
            test_phone: $('input[name="phone_numbers"]').val().split(',')[0], // 使用第一个手机号进行测试
            csrfmiddlewaretoken: '{{ csrf_token }}'
        };

        // 禁用测试按钮
        const $button = $(this);
        $button.prop('disabled', true);
        $button.html('<i class="fas fa-spinner fa-spin"></i> 测试中...');

        $.ajax({
            url: '{% url "test_sms_config" %}',
            type: 'POST',
            data: smsData,
            success: function(response) {
                if (response.status === 'success') {
                    alert('短信配置测试成功！测试短信已发送。');
                } else {
                    alert('短信配置测试失败：' + response.message);
                }
            },
            error: function() {
                alert('测试请求发送失败，请检查网络连接。');
            },
            complete: function() {
                // 恢复测试按钮
                $button.prop('disabled', false);
                $button.html('<i class="fas fa-paper-plane"></i> 测试短信配置');
            }
        });
    });

    // 保存通知配置
    $('#saveNotification').click(function() {
        const formData = new FormData($('#notificationForm')[0]);
        const url = formData.get('id') ? '{% url "update_notification" %}' : '{% url "create_notification" %}';

        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.status === 'success') {
                    location.reload();
                } else {
                    alert(response.message);
                }
            }
        });
    });

    // 编辑通知配置
    $('.edit-notification').click(function() {
        const id = $(this).data('id');
        $.get(`{% url "get_notification" %}?id=${id}`, function(data) {
            $('#notificationId').val(data.id);
            $('input[name="name"]').val(data.name);
            $('#notificationType').val(data.type).trigger('change');
            
            // 设置告警级别
            data.alert_levels.forEach(level => {
                $(`#level${level.charAt(0).toUpperCase() + level.slice(1)}`).prop('checked', true);
            });
            
            // 设置类型特定的配置
            if (data.type === 'email') {
                $('input[name="email_recipients"]').val(data.config.recipients);
                // 设置SMTP配置
                if (data.config.smtp) {
                    $('input[name="smtp_host"]').val(data.config.smtp.host);
                    $('input[name="smtp_port"]').val(data.config.smtp.port);
                    $('input[name="smtp_username"]').val(data.config.smtp.username);
                    $('input[name="smtp_password"]').val(data.config.smtp.password);
                    $('input[name="smtp_from_email"]').val(data.config.smtp.from_email);
                    $('input[name="smtp_use_tls"]').prop('checked', data.config.smtp.use_tls);
                }
            } else if (data.type === 'sms') {
                $('input[name="phone_numbers"]').val(data.config.phone_numbers);
                // 设置短信API配置
                if (data.config.sms) {
                    $('input[name="sms_api_url"]').val(data.config.sms.api_url);
                    $('input[name="sms_api_key"]').val(data.config.sms.api_key);
                    $('input[name="sms_api_secret"]').val(data.config.sms.api_secret);
                }
            } else if (data.type === 'webhook') {
                $('input[name="webhook_url"]').val(data.config.url);
                $('select[name="webhook_method"]').val(data.config.method);
                $('textarea[name="webhook_headers"]').val(JSON.stringify(data.config.headers, null, 2));
            }
        });
    });

    // 删除通知配置
    $('.delete-notification').click(function() {
        if (confirm('确定要删除这个通知配置吗？')) {
            const id = $(this).data('id');
            $.post('{% url "delete_notification" %}', {
                id: id,
                csrfmiddlewaretoken: '{{ csrf_token }}'
            }, function(response) {
                if (response.status === 'success') {
                    location.reload();
                } else {
                    alert(response.message);
                }
            });
        }
    });

    // 切换通知状态
    $('.toggle-status').change(function() {
        const id = $(this).data('id');
        const is_active = $(this).prop('checked');
        
        $.post('{% url "toggle_notification" %}', {
            id: id,
            is_active: is_active,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        }, function(response) {
            if (response.status !== 'success') {
                alert(response.message);
                location.reload();
            }
        });
    });

    // 测试通知
    $('.test-notification').click(function() {
        const id = $(this).data('id');
        $.post('{% url "test_notification" %}', {
            id: id,
            csrfmiddlewaretoken: '{{ csrf_token }}'
        }, function(response) {
            alert(response.message);
        });
    });
});
</script>
{% endblock %} 